import random

import requests
from django.core.cache import cache

from project import config
from worker import call_by_worker

def get_verify_code(length=6):
  #生产一个6位验证码
  return random.randrange(10**(length-1),10**length)

#@call_by_worker
def send_verify_code(phonenum):
  print('发送验证码')
  #异步发送验证码  celery用法：celery worker -A worker -l info

  vcode=get_verify_code(4)
  print('++++++++++',vcode)
  key='VerifyCode-%s' % phonenum
  saved_vcode = cache.get(key)
  print(saved_vcode,type(saved_vcode),'11111111111')
  if saved_vcode:
    return False
  else:
    cache.set(key, vcode, 180)  # 180秒为缓存过期时间是3分钟
    sms_cfg = config.HY_SMS_PARAMS.copy()
    sms_cfg['content'] = sms_cfg['content'] % vcode
    sms_cfg['mobile'] = phonenum
    response = requests.post(config.HY_SMS_URL1, data=sms_cfg)
    print('*******', response)
    print('-------------', response.json())
    return response


def check_vcode(phonenum,vcode):
  #检查验证码
  key='VerifyCode-%s'%phonenum
  saved_vcode=str(cache.get(key))

  print('++++++++++++++',saved_vcode,type(saved_vcode))
  if saved_vcode==vcode:
    print('----------------')
    return True
  else:
    print('---++++++++-----')
    return False